package com.tarena.lbs.content.service.impl;

import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.common.enums.Roles;
import com.tarena.lbs.common.principle.UserPrinciple;
import com.tarena.lbs.common.utils.AuthenticationContextUtils;
import com.tarena.lbs.content.dao.repository.ArticleRepository;
import com.tarena.lbs.content.pojo.param.ArticleContentParam;
import com.tarena.lbs.content.pojo.po.ArticleContentPO;
import com.tarena.lbs.content.pojo.query.ArticleQuery;
import com.tarena.lbs.content.pojo.vo.ArticleVO;
import com.tarena.lbs.content.service.ArticleService;
import io.jsonwebtoken.lang.Assert;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleRepository articleRepository;
    @Override
    public void save(ArticleContentParam param) {
        log.info("保存文章信息: {}", param);
        checkRole(Roles.SHOP);
        ArticleContentPO po = new ArticleContentPO();
        BeanUtils.copyProperties(param, po);
        log.info("保存文章信息: {}", po);
        po.setCreateTime(new Date());
        articleRepository.save(po);
    }

    private void checkRole(Roles roles) {
        log.debug("检查用户身份是否为商户");
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        log.info("当前用户信息: {}", userPrinciple);
        Assert.isTrue(userPrinciple != null, new BusinessException("-1", "用户未登录或认证已过期").getMessage());
        if (userPrinciple.getRole() != null){
            Assert.isTrue(userPrinciple.getRole() == roles, new BusinessException("-1", "用户权限不足").getMessage());
        }
    }

    @Override
    public List<ArticleVO> selectList(ArticleQuery articleQuery) {
        List<ArticleVO> articleVOS = articleRepository.selectList(articleQuery);
        return articleVOS;
    }

    @Override
    public ArticleVO selectById(String id) {
        ArticleVO avo=articleRepository.selectById(id);
        return avo;
    }
}
